package com.wryyyyy.service.impl;

import com.wryyyyy.dto.AddMaterialDTO;
import com.wryyyyy.entity.Material;
import com.wryyyyy.mapper.MaterialMapper;
import com.wryyyyy.service.IMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wryyyyy
 * @since 2023-11-12
 */
@Service
public class MaterialServiceImpl extends ServiceImpl<MaterialMapper, Material> implements IMaterialService {
    @Resource
    MaterialMapper materialMapper;

    @Override
    public Double calculatePrice(List<AddMaterialDTO> addMaterialDTOS) {
        double sumPrice = 0.0;

        if (addMaterialDTOS.isEmpty()) {
            return sumPrice;
        }

        List<String> materialIds = new ArrayList<>();
        Map<String, Double> weightMap = new HashMap<>();
        Map<String, Double> priceMap = new HashMap<>();
        for (AddMaterialDTO obj : addMaterialDTOS) {
            materialIds.add(obj.getId());
            weightMap.put(obj.getId(), obj.getWeight());
        }
        List<Material> materials = materialMapper.selectMaterials(materialIds);
        for (Material material : materials) {
            priceMap.put(material.getId(), material.getPrice());
        }
        for (String id : materialIds) {
            sumPrice += weightMap.get(id) * priceMap.get(id);
        }
        return sumPrice;
    }
}
